package it.unisalento.appsalento.activity;

import it.unisalento.R;
import it.unisalento.appsalento.constants.Constants;
import it.unisalento.appsalento.asynctask.UserLoginTask;
import it.unisalento.appsalento.model.Utente;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

/**
 * <p><b>Description</b>: Activity Che visualizza la pagina di login o effettua direttamente 
 * la login se l'utente ha impostato il check rimani connesso
 * </p>
 * 
 * @author Alberto Gianfranco Meleleo
 */
public class LoginActivity extends Activity {

	/**
	 * The default email to populate the email field with.
	 */
	private static final String EMAIL_REGEX = "[a-zA-Z0-9._-]+@[a-z\\.]+\\.+[a-z]+";

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask mAuthTask = null;


	private String digitUsername;
	private String digitPassword;
	private Intent intent;

	private EditText mEmailView;
	private EditText mPasswordView;
	private CheckBox rimaniConnesso;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		intent = new Intent(this, MainActivity.class);

		SharedPreferences pref = getSharedPreferences(Constants.PREFS_NAME,MODE_MULTI_PROCESS);   
		String username = pref.getString(Constants.PREF_USERNAME, null);
		String password = pref.getString(Constants.PREF_PASSWORD, null);

		if (username != null && password != null) {
			digitUsername = username;
			digitPassword = password;
			attemptLogin();
		}else{
			
			if (App.utente != null) {
				startActivity(intent);
				finish();
			} else if(digitUsername == null || "".equals(digitUsername)){
				setContentView(R.layout.activity_login);
				rimaniConnesso =  (CheckBox) findViewById(R.id.check_rimani_connesso);
	
				// Set up the login form.
				mEmailView = (EditText) findViewById(R.id.email);
				mEmailView.setText(digitUsername);
	
				mPasswordView = (EditText) findViewById(R.id.password);
				mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
							@Override
							public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
								if (id == R.id.login || id == EditorInfo.IME_NULL) {
									attemptLogin();
									return true;
								}
								return false;
							}
						});
	
				mLoginFormView = findViewById(R.id.login_form);
				mLoginStatusView = findViewById(R.id.login_status);
				mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
	
				findViewById(R.id.sign_in_button).setOnClickListener(
						new View.OnClickListener() {
							@Override
							public void onClick(View view) {
								//rimaniConnesso =  (CheckBox) findViewById(R.id.checkRimaniConnesso);
								InputMethodManager inputManager = (InputMethodManager)
		                                  getSystemService(Context.INPUT_METHOD_SERVICE); 
	
								inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
		                                     InputMethodManager.HIDE_NOT_ALWAYS);
								attemptLogin();
							}
						});
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		return true;
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}
		boolean cancel = false;
		View focusView = null;
		boolean mailControl = true;
		
		// Reset errors.
		if(mEmailView != null){
			mEmailView.setError(null);
			mailControl = mEmailView.getText().toString().matches(EMAIL_REGEX);
		}
		if(mPasswordView != null){
			mPasswordView.setError(null);
		}
		if(digitUsername == null || "".equals(digitUsername) || !mailControl){
			// Store values at the time of the login attempt.
			digitUsername = mEmailView.getText().toString();
			digitPassword = mPasswordView.getText().toString();
			// Check for a valid password.
			if (TextUtils.isEmpty(digitPassword)) {
				mPasswordView.setError(getString(R.string.error_field_required));
				focusView = mPasswordView;
				cancel = true;
			}

			// Check for a valid email address.
			if (TextUtils.isEmpty(digitUsername)) {
				mEmailView.setError(getString(R.string.error_field_required));
				focusView = mEmailView;
				cancel = true;
			}else if(!mailControl){
				mEmailView.setError(getString(R.string.error_email_required));
				focusView = mEmailView;
				cancel = true;
			}
			if (cancel) {
				focusView.requestFocus();
			}else{
				mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
				showProgress(true);
			}
		}

		if (!cancel) {
				
			App.utente = new Utente();
			App.utente.setUsername(digitUsername);
			App.utente.setPassword(digitPassword);
			
			mAuthTask = new UserLoginTask(this,this,intent,(rimaniConnesso != null && rimaniConnesso.isChecked()));
			
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
				mAuthTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
			}else{
				mAuthTask.execute((Void[])null);
			}
			
//			mAuthTask.execute((Void) null);

		}

	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if(mLoginStatusView != null){
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
				int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
				
					mLoginStatusView.setVisibility(View.VISIBLE);
					mLoginStatusView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
								@Override
								public void onAnimationEnd(Animator animation) {
									mLoginStatusView.setVisibility(show ? View.VISIBLE
											: View.GONE);
								}
							});
		
					mLoginFormView.setVisibility(View.VISIBLE);
					mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
								@Override
								public void onAnimationEnd(Animator animation) {
									mLoginFormView.setVisibility(show ? View.GONE
											: View.VISIBLE);
								}
							});
				} else {
					// The ViewPropertyAnimator APIs are not available, so simply show
					// and hide the relevant UI components.
					mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
					mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
				}
		}
	}

}
